﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Authorize.Core.Extensions;
using Microsoft.AspNetCore.Http;

namespace Authorize.Core.Web
{
    public class BaseUrlMiddleware : IMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly string _publicOrigin;

        public BaseUrlMiddleware(RequestDelegate next, string publicOrign)
        {
            _next = next;
            _publicOrigin = publicOrign;
        }

        public async Task Invoke(HttpContext context)
        {

        }

        public Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (!string.IsNullOrWhiteSpace(_publicOrigin))
            {
                var reg = new Regex(@"(https?)://(\w+\..*?\.com)(/?.*)");
                var uris = reg.Replace(_publicOrigin, "$1,$2,$3").Split(",");
                context.Request.Scheme = uris[0];
                context.Request.Host = new HostString(uris[1]);
                context.Request.PathBase = new PathString(uris[2].EnsureTrailingSlash());
            }
            return _next(context);
        }
    }
}
